<?php

declare(strict_types=1);

namespace app\common\model;

use think\Model;
use think\response\Json;

/**
 * @mixin \think\Model
 */
class Coupon extends Base
{

    protected $name = 'coupon';

    public function getTypesNameAttr($value, $data)
    {
        if ($data['types'] == 1) {
            $name = '普通优惠券';
        } else if ($data['types'] == 2) {
            $name = '订单满减券';
        } else if ($data['types'] == 3) {
            $name = '积分现金券';
        } else {
            $name = '未知';
        }
        return $name;
    }
    public static function savepsot($param)
    {
        parent::startTrans();
        try {
            if(empty($param['types'])){
                return ['code' => -1, 'msg' => '请选择优惠券类型！'];
            }
            if (empty($param['product_ids'])) {
                return ['code' => -1, 'msg' => '请选择优惠券商品！'];
            }
            $data['end_times'] = $param['end_time'];
            $data['num'] = $param['num'];
            $data['receive'] = $param['receive'];
            if ($param['types'] == 2) {
                $data['term_money'] = $param['term_money'];
            } else {
                $data['term_money'] = 0;
            }
            $data['end_time'] = strtotime($param['end_time']);
            $data['money'] = $param['money'];
            $data['money'] = $param['money'];
            $data['title'] = $param['title'];
            $data['sort'] = $param['sort'];
            $data['time'] = $param['time'];
            $data['types'] = $param['types'];
            $data['sale_money'] = $param['sale_money'];

            $data['product_ids'] = implode(',', $param['product_ids']);
            if (isset($param['level_ids']) && !empty($param['level_ids'])) {
                $data['level_ids'] = implode(',', $param['level_ids']);
            }
            if (isset($param['id']) && $param['id'] != 0) {
                $data['id'] = $param['id'];
                $find = parent::update($data);
            } else {
                $find = parent::create($data);
            }
            CouponProduct::couponProductAdd($find['id'], $param['product_ids']);
            parent::commit();
            return ['code' => 1, 'msg' => '操作成功！'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}
